#import "WX.h"
#import "WXApi.h"
#import "WXManage.h"

#pragma mark - WX
@interface WX()

@end
@implementation WX
static WX *wx = nil;
static NSString *WEIXIN_KEY = @"";

+(instancetype)WXSingle {
    return wx;
}

- (void) pluginInitialize
{
    NSLog(@"WX->%@", @"init");
    WEIXIN_KEY = [self.commandDelegate.settings objectForKey:[@"WEIXIN_KEY" lowercaseString]];
    [WXApi registerApp:WEIXIN_KEY];
    wx = self;
}

-(void) login:(CDVInvokedUrlCommand*)command
{
    NSLog(@"WX->%@", @"login");
    //构造SendAuthReq结构体
    self.urlCommand = command;
    NSLog(@"command%@", self.urlCommand);
    SendAuthReq* req =[[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo";
    req.state = @"web_app_state";
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}

-(void) isInstalled:(CDVInvokedUrlCommand*)command
{
    NSLog(@"WX->%@", @"inInstalled");
    bool result = [WXApi isWXAppInstalled];
    CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsBool:result];
    [self.commandDelegate sendPluginResult: pluginResult callbackId: command.callbackId];
}

-(void) loginResult:(SendAuthResp *)resp
{
    NSLog(@"WX->%@", @"loginResult");
    NSLog(@"resp%@", resp);
    NSLog(@"command%@", self.urlCommand);
    if (resp.errCode == 0) {
        NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
        [result setValue:resp.state forKey:@"state"];
        [result setValue:resp.code forKey:@"code"];
        [result setValue:resp.lang forKey:@"lang"];
        [result setValue:resp.country forKey:@"country"];
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsDictionary:result];
        [self.commandDelegate sendPluginResult: pluginResult callbackId: self.urlCommand.callbackId];
    } else {
        CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus: CDVCommandStatus_ERROR messageAsString:@"error"];
        [self.commandDelegate sendPluginResult: pluginResult callbackId: self.urlCommand.callbackId];
    }
}
@end
